package ink.fujisann.learning.stock.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ink.fujisann.learning.stock.pojo.CoinBase;
import ink.fujisann.learning.stock.repository.CoinBaseRepository;
import ink.fujisann.learning.stock.service.CoinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CoinServiceImpl implements CoinService {
    private CoinBaseRepository coinBaseRepository;

    @Autowired
    public void setCoinBaseRepository(CoinBaseRepository coinBaseRepository) {
        this.coinBaseRepository = coinBaseRepository;
    }

    @Override
    public void insertCoinBase() {
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 没有客户端端标志(存在请求头即可)，403
        headers.set("User-Agent", "");
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        // 调用火币接口查询数据
        ResponseEntity<JSONObject> entity = template.exchange("https://open.huobigroup.com/v1/common/currencys",
                HttpMethod.GET, httpEntity, JSONObject.class);
        JSONObject body = entity.getBody();
        JSONArray data = Optional.ofNullable(body).orElseThrow(RuntimeException::new)
                .getJSONArray("data");

        // 构建批量新增数据
        List<CoinBase> insertBatch = data.stream().map(o -> {
            String coinCode = (String) o;
            CoinBase coinBase = new CoinBase();
            coinBase.setCoinCode(coinCode);
            return coinBase;
        }).collect(Collectors.toList());
        coinBaseRepository.saveAll(insertBatch);
    }
}
